<template>
  <div class="user-set">
    <el-card class="setting-card">
      <template #header>
        <div class="card-header">
          <span>用户设置</span>
        </div>
      </template>
      
      <el-form :model="userForm" label-width="100px">
        <!-- 头像设置 -->
        <el-form-item label="当前头像">
          <div class="avatar-container">
            <el-avatar
              :size="100"
              :src="userForm.profile_picture_url"
              @error="() => true"
            >
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
            </el-avatar>
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              accept="image/*"
            >
              <el-button type="primary" class="mt-2">更换头像</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 基本信息设置 -->
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" disabled></el-input>
        </el-form-item>

        <!-- 修改密码部分 -->
        <el-form-item label="原密码">
          <el-input v-model="userForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
        </el-form-item>

        <el-form-item label="新密码">
          <el-input v-model="userForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserInfo } from '../api/auth'
import { postFormDataRequest, PostRequest } from '../api/api'
import apiClient from '../api/api'

export default {
  data() {
    return {
      userForm: {
        username: '',
        email: '',
        oldPassword: '',
        newPassword: '',
        profile_picture_url: '',
      }
    }
  },

  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await apiClient.get('/user/info')
        const userInfo = response.data
        console.log('用户信息', userInfo)
        // 更新表单数据
        let profileUrl = userInfo.profilePictureUrl
        if (profileUrl && profileUrl.startsWith('https://')) {
          profileUrl = 'http://' + profileUrl.substring(8)
        }
        this.userForm = {
          ...this.userForm,
          username: userInfo.username,
          email: userInfo.email,
          profile_picture_url: profileUrl,
        }

        // 更新本地存储
        localStorage.setItem('userInfo', JSON.stringify({
          username: userInfo.username,
          email: userInfo.email,
          profile_picture_url: userInfo.profilePictureUrl
        }))
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },

    async handleAvatarChange(file) {
      console.log('头像上传', file)
      try {
        // 创建 FormData 对象并添加文件
        const formData = new FormData()
        formData.append('file', file.raw)
        
        console.log('头像上传', formData)
        // 调用上传接口
        const url = await postFormDataRequest('/jobs/upload', formData)
        console.log('头像上传成功，返回的URL:', url)

        // 直接使用返回的URL
        this.userForm.profile_picture_url = url
      } catch (error) {
        console.log('头像上传失败', error)
        alert('头像上传失败')
      }
    },

    async saveSettings() {
      try {
        // 如果有新密码，先验证
        if (this.userForm.newPassword) {
          if (!this.userForm.oldPassword) {
            alert('请输入原密码')
            return
          }
          if (this.userForm.oldPassword === this.userForm.newPassword) {
            alert('新密码不能与原密码相同')
            return
          }
        }

        // 构建更新数据
        const updateData = {
          username: this.userForm.username,
          profile_picture_url: this.userForm.profile_picture_url
        }

        // 如果有新密码，则添加到更新数据中
        if (this.userForm.newPassword) {
          updateData.password = this.userForm.newPassword
        }

        // 调用更新接口
        await PostRequest('/update-user-info', updateData)
        alert('设置保存成功')

        // 清空密码字段
        this.userForm.oldPassword = ''
        this.userForm.newPassword = ''

        // 更新本地存储的用户信息
        localStorage.setItem('userInfo', JSON.stringify({
          ...JSON.parse(localStorage.getItem('userInfo') || '{}'),
          profile_picture_url: this.userForm.profile_picture_url
        }))
      } catch (error) {
        console.error('保存设置失败:', error)
        alert('保存设置失败，请重试')
      }
    }
  },

  async mounted() {
    // 获取用户信息
    await this.fetchUserInfo()
  }
}
</script>

<style scoped>
.user-set {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.setting-card {
  max-width: 600px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  font-size: 18px;
  color: #303133;
  padding: 15px 0;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
  background-color: #fafafa;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.avatar-container:hover {
  background-color: #f0f2f5;
}

.el-avatar {
  border: 4px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.el-avatar:hover {
  transform: scale(1.05);
}

.avatar-uploader {
  text-align: center;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input {
  transition: all 0.3s ease;
}

.el-input:hover {
  transform: translateX(5px);
}

.el-button {
  padding: 12px 25px;
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 768px) {
  .setting-card {
    margin: 10px;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
